#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from email_validator import EmailNotValidError, validate_email
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from backend.app.crud import article_crud, category_crud, comment_crud, friend_crud, subscription_crud, tag_crud
from backend.app.datebase.db import get_db
from backend.app.model import About
from backend.app.schema import Response200, Response403, Response404, Response500
from backend.app.schema.comment import CreateComment
from backend.app.schema.subscription import CreateSubscription, DeleteSub
from backend.app.utils.comments_check import DFAFilter

blog = APIRouter()

"""
说明：游客
"""


@blog.get('/article_list', summary='获取文章分页列表')
async def get_article(page: int = 1, limit: int = 10, db: Session = Depends(get_db)):
    data = article_crud.get_articles(db, page, limit)
    count = article_crud.get_articles_count(db)
    return Response200(msg='获取文章成功', data={"articles": data, 'count': count})


@blog.get('/hot_list', summary='获取热门文章列表')
async def get_hot(db: Session = Depends(get_db)):
    data = article_crud.get_hot(db)
    return Response200(data=data)


@blog.get('/new_list', summary='获取新文章列表')
async def get_hot(db: Session = Depends(get_db)):
    data = article_crud.get_new(db)
    return Response200(data=data)


@blog.get('/rank_list', summary='获取文章浏览排行列表')
async def get_hot(db: Session = Depends(get_db)):
    data = article_crud.get_rank(db)
    return Response200(data=data)


@blog.get('/article/{article_id}', summary='获取文章详情')
async def get_blog_list(article_id: int, db: Session = Depends(get_db)):
    article = article_crud.get_article_for_id(db, article_id)
    if article is not None:
        article.view_num += 1
        db.commit()
        category = category_crud.get_category_by_id(db, article.category_id)
        comment_num = comment_crud.get_comments_count(db, article_id)
        comments = comment_crud.get_comments_by_article_id(db, article_id)
        return Response200(data={'article': article, 'category': category,
                                 'comment': {'comment_num': comment_num, 'comments': comments}})
    return Response404(msg='没有此文章')


@blog.get('/tag/{tag_id}/list', summary='获取标签文章列表')
async def get_tag(tag_id: int, db: Session = Depends(get_db)):
    tag = tag_crud.get_tag_for_id(db, tag_id)
    if tag is not None:
        data = article_crud.get_articles_by_tag_id(db, tag_id)
        count = article_crud.get_articles_by_tag_id_count(db, tag_id)
        return Response200(data={"articles": data, 'count': count})
    return Response404(msg='没有此标签')


@blog.get('/category/{category_id}/list', summary='获取分类文章分页列表')
async def get_category(category_id: int, page: int = 1, limit: int = 10, db: Session = Depends(get_db)):
    category = category_crud.get_category_for_id(db, category_id)
    if category is not None:
        data = article_crud.get_articles_by_category_id(db, category_id, page, limit)
        count = article_crud.get_articles_by_category_id_count(db, category_id)
        return Response200(msg='获取分类文章成功', data={"articles": data, 'count': count})
    return Response404(msg='没有此分类')


@blog.post('/comment', summary='新增评论')
async def create_comment(post: CreateComment, article_id: int, db: Session = Depends(get_db)):
    if comment_crud.get_comment(db):
        try:
            validate_email(post.email)
        except EmailNotValidError:
            raise HTTPException(status_code=403, detail='邮箱输入有误，请重新输入')
        if article_crud.get_article_by_id(db, article_id):
            # 评论敏感词过滤
            post.comment = DFAFilter().check_comments(post.comment)
            if "*" in DFAFilter().check_comments(post.user_name):
                post.user_name = '信球'
            comment_crud.create_comment(db, post, article_id)
            return Response200(msg='新增评论成功', data=post)
        return Response403(msg='评论失败，不存在对应的文章')
    return Response500(msg='新增评论失败')


@blog.get('/comment/<int:pk>', summary='获取评论')
async def get_comment(article_id: int, db: Session = Depends(get_db)):
    if article_crud.get_article_by_id(db, article_id):
        data = comment_crud.get_comments(db, article_id)
        return Response200(msg='获取评论成功', data=data)
    return Response404(msg='文章不存在')


@blog.get('/new_comment', summary='获取最新评论')
async def get_new_comment(db: Session = Depends(get_db)):
    comments = comment_crud.get_new_comment(db)
    return Response200(msg='获取最新评论成功', data=comments)


@blog.post('/subscription', summary='邮箱订阅')
async def subscription_record(email: CreateSubscription, db: Session = Depends(get_db)):
    try:
        validate_email(email.email)
    except EmailNotValidError:
        return Response403(msg='邮箱输入有误，请重新输入')
    if subscription_crud.check_sub_email(db, email):
        return Response403(msg='此邮箱已订阅，不能重复订阅')
    subscription_crud.create_sub(db, email)
    return Response200(msg=f'感谢 {email.email}，您已订阅成功')


@blog.delete('/unsubscription', summary='取消邮箱订阅')
async def unsubscription(email: DeleteSub, db: Session = Depends(get_db)):
    try:
        validate_email(email.email)
    except EmailNotValidError:
        return Response403(msg='邮箱输入有误，请重新输入')
    if not subscription_crud.check_sub_email(db, email):
        return Response403(msg='此邮箱未订阅')
    subscription_crud.delete_sub(db, email)
    return Response200(msg=f'邮箱 {email.email}，您已取消订阅成功')


@blog.get('/about', summary='获取关于')
async def get_about(db: Session = Depends(get_db)):
    data = db.query(About).all()
    return Response200(msg='获取关于成功', data=data)


@blog.get('/friend', summary='获取友链')
async def get_friend(db: Session = Depends(get_db)):
    data = friend_crud.get_all(db)
    return Response200(msg='获取友链成功', data=data)


@blog.get('/search/{key}', summary='全局搜索')
async def search(key: str, page: int = 1, limit: int = 10, db: Session = Depends(get_db)):
    data = article_crud.get_search(db, key, page, limit)
    return Response200(msg='搜索完成', data=data)


@blog.get('/archive', summary='文章归档')
async def archive(db: Session = Depends(get_db)):
    _blog_list = article_crud.get_article_archive(db)
    archive_dict = {}
    for _blog in _blog_list:
        pub_month = _blog.date_time.strftime("%Y年%m月")
        if pub_month in archive_dict:
            archive_dict[pub_month].append(_blog)
        else:
            archive_dict[pub_month] = [_blog]
    return Response200(msg='归档成功', data=archive_dict)


@blog.get('/rss', summary='Rss', deprecated=True)
async def rss():
    pass


@blog.get('/atom', summary='Atom', deprecated=True)
async def atom():
    pass
